package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.service.ICameraOperateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 云台控制业务实现类
 *
 * @author Orange
 * @date 2021/3/9
 */

@Service
public class CameraOperateServiceImpl implements ICameraOperateService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    public RedisTemplate redisTemplate;


    /**
     * 生成post请求的JSON请求参数
     * 请求示例:
     * {
     * "id":1,
     * "name":"张耀烽"
     * }
     *
     * @return HttpEntity
     */
    public HttpEntity<Map<String, String>> generatePostJson(Map<String, String> jsonMap) {

        //如果需要其它的请求头信息、都可以在这里追加
        HttpHeaders httpHeaders = new HttpHeaders();

        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");

        httpHeaders.setContentType(type);

        HttpEntity<Map<String, String>> entity = new HttpEntity<>(jsonMap, httpHeaders);

        return entity;
    }


    /**
     * 云台移动
     *
     * @param deviceSerial 设备序列号,存在英文字母的设备序列号，字母需为大写
     * @param channelNo    通道号 默认为 1
     * @param direction    操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
     * @param speed        云台速度：0-慢，1-适中，2-快，海康设备参数不可为0 默认为 0
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Orange
     * @date 2021/3/9
     */
    public AjaxResult movement(String deviceSerial, String channelNo, Integer direction, String speed) {
        Object token = redisCache.getCacheObject("camera_access_token");
        //请求一次，rediskey值是否存在
        Boolean hasKey = redisTemplate.hasKey("camera_access_token");
        Long expire = redisTemplate.opsForValue().getOperations().getExpire("camera_access_token");
        boolean isExpired = expire > 1 ? true : false;
        if(isExpired==false){
            token=gettokey();
        }
        JSONObject jsonObject = new JSONObject();
        String uri = "https://open.ys7.com/api/lapp/device/ptz/start?accessToken=" + token
                + "&deviceSerial=" + deviceSerial + "&channelNo=" + channelNo + "&direction=" + direction + "&speed=" + speed;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);

        ResponseEntity<JSONObject> entity = restTemplate.postForEntity(uri, formEntity, JSONObject.class);

        JSONObject body = entity.getBody();
        System.out.println(body);
        return AjaxResult.success();
    }

    /**
     * 停止云台控制（提示：direction输入与云台移动一样的命令）
     *
     * @param deviceSerial 设备序列号,存在英文字母的设备序列号，字母需为大写
     * @param channelNo    通道号 默认为 1
     * @param direction    操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
     * @return AjaxResult
     * @author Orange
     * @date 2021/3/9
     */
    public AjaxResult stop(String deviceSerial, String channelNo, Integer direction) {
        Object token = redisCache.getCacheObject("camera_access_token");
        //请求一次，如果hash表里没有该区域的天气，则再去获取，如果有则直接返回
        Boolean hasKey = redisTemplate.hasKey("camera_access_token");
        Long expire = redisTemplate.opsForValue().getOperations().getExpire("camera_access_token");
        boolean isExpired = expire > 1 ? true : false;
        if(isExpired==false){
            token=gettokey();
        }
        JSONObject jsonObject = new JSONObject();
        String uri = "https://open.ys7.com/api/lapp/device/ptz/stop?accessToken=" + token
                + "&deviceSerial=" + deviceSerial + "&channelNo=" + channelNo + "&direction=" + direction;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);

        ResponseEntity<JSONObject> entity = restTemplate.postForEntity(uri, formEntity, JSONObject.class);
        JSONObject body = entity.getBody();
        return AjaxResult.success(body);

    }

    /**
     * 获取萤石云Token
     *
     * @return java.lang.Object
     * @author Orange
     * @date 2021/3/15
     */
    public Object getToken() {
        return redisCache.getCacheObject("camera_access_token");
    }

    /**
     * 设备抓图
     *
     * @param deviceSerial 设备序列号,存在英文字母的设备序列号，字母需为大写
     * @param channelNo    通道号 默认为 1
     * @return java.lang.String
     * @author Orange
     * @date 2021/3/15
     */
    public String getCapture(String deviceSerial, String channelNo) {
        Object token = redisCache.getCacheObject("camera_access_token");
        //请求一次，如果hash表里没有该区域的天气，则再去获取，如果有则直接返回
        Boolean hasKey = redisTemplate.hasKey("camera_access_token");
        Long expire = redisTemplate.opsForValue().getOperations().getExpire("camera_access_token");
        boolean isExpired = expire > 1 ? true : false;
        if(isExpired==false){
            token=gettokey();
        }
        String uri = "https://open.ys7.com/api/lapp/device/capture?accessToken=" + token
                + "&deviceSerial=" + deviceSerial + "&channelNo=" + channelNo;
        JSONObject jsonObject = restTemplate.postForObject(uri, null, JSONObject.class);
        Object data = jsonObject.get("data");

        Map map = JSON.parseObject(JSON.toJSONString(data), Map.class);

        return map.get("picUrl").toString();
    }

    public String gettokey() {
        Object token = redisCache.getCacheObject("camera_access_token");
        String uri = "https://open.ys7.com/api/lapp/token/get?appKey=07a6b11df32e4d94bd3146155a2143f6&appSecret=ea6fcb33851355deee3403fd258b4914";
        JSONObject jsonObject = restTemplate.postForObject(uri, null, JSONObject.class);
        Object data = jsonObject.get("data");

        Map map = JSON.parseObject(JSON.toJSONString(data), Map.class);

        return map.get("accessToken").toString();
    }
}
